package com.photoeditor.demo.util;

import com.photoeditor.demo.statistics.StatisticsUtils;

import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.List;

import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_USEVPN;

/**
 * Created by dell on 2017/11/28.
 */

public class VpnUtils {

    private static VpnUtils instance;

    private boolean isVpnUsed = false;

//    private NetWorkStateReceiver netWorkStateReceiver;

    private VpnUtils() {

    }

    public synchronized static VpnUtils getInstance() {
        if (instance == null) {
            instance = new VpnUtils();
        }
        return instance;
    }

    public void init() {
//        if (netWorkStateReceiver == null) {
//            netWorkStateReceiver = new NetWorkStateReceiver();
//            netWorkStateReceiver.setNetWorkStateListener(new NetWorkStateReceiver.NetWorkStateListener() {
//                @Override
//                public void onNetWorkStateChange() {
//                    checkVpnUsed();
//                }
//            });
//            IntentFilter intentFilter = new IntentFilter();
//            intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
//            ComponentContext.getContext().registerReceiver(netWorkStateReceiver, intentFilter);
//        }
        // 初始化获
        checkVpnUsed();
    }

    public boolean isVpnUsed() {
        return isVpnUsed;
    }

    private void checkVpnUsed() {
        try {
            List<NetworkInterface> niList = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface networkInterface : niList) {
                if (!networkInterface.isUp() || networkInterface.getInterfaceAddresses().size() == 0) {
                    continue;
                }
                String interfaceName = networkInterface.getName();
                if (interfaceName.contains("tun") || interfaceName.contains("ppp")
                        || interfaceName.contains("tap")) {
                    StatisticsUtils.statisticsCustomFunction(STATISTIC_EVENT_USEVPN);
                    return;
                }
            }
        } catch (SocketException ex) {
            ex.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
